﻿using CarEdge.Infrastructure.Attr;
using CarEdge.Infrastructure.Dto.Request.product;
using CarEdge.Infrastructure.Dto.Response;
using CarEdge.Infrastructure.Dto.Response.Product;
using CarEdge.Infrastructure.EFCore.MySql;
using CarEdge.Infrastructure.IOC.Product;
using CarEdge.Service.Interface.Product;
using Crm.Infrastructure.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Xml.Linq;
using System.Xml.Schema;

namespace CarEdge.Service.Instance.Product
{
    [Inject_]
    public class Product_Service : Base_Service, I_Product_EFCore
    {
        private readonly Product_IOC _product_ioc;
        private readonly IConfiguration _configuration;

        public Product_Service(Product_IOC product_ioc, IConfiguration configuration)
        {
            _product_ioc = product_ioc;
            _configuration = configuration;
        }
        /// <summary>
        /// 添加产品
        /// </summary>
        /// <param name="product">产品</param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Add_Product(Product_Response_Dto product)
        {

            SysProduct pp = new SysProduct();
            pp.Pid = Config.GUID2();
            pp.Pprice = product.pprice;
            pp.PDuration = product.pDuration;
            pp.Pislist = 0;
            pp.Pexplain = product.pexplain;
            pp.Pcreatetime = DateTime.Now;
            pp.Pcount = product.pCount;
            pp.Pdata = product.pDuration > 0 ? null : DateTime.Parse(product.pData!);
            pp.Pimage = string.Join(',', product.pimg!);
            pp.Pname = product.pname;
            pp.Psales = 0;
            pp.Pshelf = product.pshelf;
            pp.Ptid = product.ptype;
            pp.Pshelf = product.pDuration == 0 ? 0 : product.pshelf;
            pp.PisTop = 0;
            pp.Pno = product.pno;
            pp.Ptype = product.pDuration == 0 ? 2 : 1;
            _product_ioc._sys_product_EFCore.Add(pp);
            var res = await _product_ioc._sys_product_EFCore.SaveChangesAsync();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");

        }
        /// <summary>
        /// 添加产品类型
        /// </summary>
        /// <param name="ptoducttype"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Add_Product_Type(Product_Type_Response_Dto ptoducttype)
        {
            var iq = await _product_ioc._sys_Product_Type_EFCore.QueryAll(d => d.Ptid == ptoducttype.ptpid).SingleAsync();
            var data = new SysProductType()
            {
                Ptid = Config.GUID(),
                PtcreateTime = DateTime.Now,
                Ptname = ptoducttype.name,
                Ptexplain = ptoducttype.explain,
                PtParentId = ptoducttype.ptpid,
                PtIsTime = iq.PtIsTime == 0 ? 0 : 1,
                PtDesc = null
            };

            _product_ioc._sys_Product_Type_EFCore.Add(data);
            var res = await _product_ioc._sys_Product_Type_EFCore.SaveChangesAsync();
            return Result(res > 0 ? 1 : 0, res > 0 ? "添加成功" : "添加失败");
        }

        /// <summary>
        /// 批量/单个 删除产品
        /// </summary>
        /// <param name="pp">产品</param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Delete_Product(IEnumerable<string?>? ids)
        {
            var product = await _product_ioc._sys_product_EFCore.QueryAll(d => ids!.Contains(d.Pid) && d.Pislist == 0).ToListAsync();
            _product_ioc._sys_product_EFCore.DeleteRange(product);
            var result = _product_ioc._sys_product_EFCore.SaveChanges();
            return Result(result > 0 ? 1 : 0, result > 0 ? "操作成功" : "操作失败");
        }

        /// <summary>
        /// 获取产品详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Get_Product(string id)
        {
            var product = await _product_ioc._sys_product_EFCore.QueryAll(d => d.Pid == id).SingleOrDefaultAsync();
            Product_Response_Dto data = new Product_Response_Dto()
            {
                pid = id,
                pCount = product!.Pcount,
                pimg = product.Pimage?.Split(',').ToArray(),
                pcreatetime = product.Pcreatetime.ToString(),
                pData = product.Pdata.ToString(),
                pDuration = product.PDuration,
                pno = product.Pno,
                pshelf = product.Pshelf,
                PIstop = product.PisTop,
                pexplain = product.Pexplain,
                pislist = product.Pislist,
                pname = product.Pname,
                pprice = product.Pprice,
                psales = product.Psales,
                ptid = product.Ptid,
                //ptype=product.Ptype.ToString(),
                ptname = _product_ioc._sys_Product_Type_EFCore.QueryAll(a => a.Ptid == product.Ptid).Select(a => a.Ptname).First(),
            };


            for (int i = 0; i < data.pimg!.Length; i++)
            {
                data.pimg.Append(_configuration["FileStorage:UploadPath"] + i).ToArray();
            }


            return Result(1, "ok", data: data);

        }

        /// <summary>
        /// 获取所有产品
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_ProductAll(int page = 1, int limit = 10, string key = "")
        {
            var product = await _product_ioc._sys_product_EFCore.QueryAll(out int total, page, limit, false, o => o.Pcreatetime, d => d.Pname.Contains(key)).ToListAsync();


            List<Product_Response_Dto> data = new List<Product_Response_Dto>();
            product.ForEach(d =>
            {
                data.Add(new Product_Response_Dto
                {
                    pid = d.Pid,
                    pname = d.Pname,
                    pCount = d.Pcount,
                    pcreatetime = d.Pcreatetime!.Value.ToString("yyyy-MM-dd HH:mm"),
                    pData = d.Pdata == null ? "" : d.Pdata!.Value.ToString("yyyy-MM-dd HH:mm"),
                    pexplain = d.Pexplain,
                    pimg = d.Pimage!.Split(','),
                    pislist = d.Pislist,
                    pprice = d.Pprice,
                    psales = d.Psales,
                    pshelf = d.Pshelf,
                    pDuration = d.PDuration,
                    pno = d.Pno,
                    PIstop = d.PisTop,
                    ptid = d.Ptid,
                    ptype=d.Ptype.ToString(),
                });
            });
            var ptid = data.Select(d => d.ptid).ToList();

            var ptype = await _product_ioc._sys_Product_Type_EFCore.QueryAll(d => ptid.Contains(d.Ptid)).ToListAsync();

            data.ForEach(d =>
            {
                d.ptname = ptype.Where(e => e.Ptid == d.ptid).SingleOrDefault()?.Ptname;

            });


            return Result(1, "ok", new
            {
                data,
                total
            });
        }
        /// <summary>
        /// 批量/单个 上/下架
        /// </summary>
        /// <param name="product">只需要传你需要上/下架的产品ID就行</param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Product_Islist(IEnumerable<string?>? ids)
        {
            var pp = await _product_ioc._sys_product_EFCore.QueryAll(d => ids!.Contains(d.Pid)).ToListAsync();

            for (int i = 0; i < pp.Count; i++)
            {
                pp[i].Pislist = pp[i].Pislist == 1 ? 0 : 1;

            }
            _product_ioc._sys_product_EFCore.UpdateRange(pp);
            var res = _product_ioc._sys_product_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }
        /// <summary>
        /// 获取父级产品类别
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Product_Type()
        {
            var pt = await _product_ioc._sys_Product_Type_EFCore.QueryAll().ToListAsync();

            var parentid = pt.Where(d => d.PtParentId == null || d.PtParentId == "").OrderBy(d => d.PtcreateTime).ToList();
            var data = new List<Product_Type_Response_Dto>();
            parentid.ForEach(d =>
            {
                data.Add(new Product_Type_Response_Dto
                {
                    id = d.Ptid,
                    name = d.Ptname,
                    istime = d.PtIsTime
                });
            });

            return Result(1, data: data);

        }
        /// <summary>
        /// 获取子级类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_children_type(string id)
        {
            var data = await _product_ioc._sys_Product_Type_EFCore.QueryAll(d => d.PtParentId == id).Select(e => new Product_Type_Response_Dto
            {
                id = e.Ptid,
                name = e.Ptname,

            }).ToListAsync();
            return Result(1, data: data);

        }
        /// <summary>
        /// 获取子级分页
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>

        public async Task<Api_Response_Dto> Get_children_Table(string id, int page = 1, int limit = 10, string key = "")
        {
            var data = await _product_ioc._sys_Product_Type_EFCore.QueryAll(out int total, page, limit, false, o => o.PtcreateTime, d => d.PtParentId == id).Select(e => new Product_Type_Response_Dto
            {
                id = e.Ptid,
                name = e.Ptname,
                explain = e.Ptexplain,
                createtime = e.PtcreateTime!.Value.ToString("yyyy-MM-dd HH:mm"),

            }).ToListAsync();

            data.ForEach(d =>
            {
                d.sumcount = _product_ioc._sys_product_EFCore.QueryAll(e => e.Ptid == d.id).Count();
            });


            return Result(1, data: new
            {
                data,
                total = data.Count(),
            });

        }

        /// <summary>
        /// 修改产品
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Update_Product(Product_Response_Dto product)
        {
            var pp = await _product_ioc._sys_product_EFCore.QueryAll(d => d.Pid == product.pid).SingleAsync();

            pp.Pexplain = product.pexplain;
            //pp.Pimage = product.pimg;
            pp.Pcount = product.pCount;
            pp.Pprice = product.pprice;
            pp.Pname = product.pname;
            pp.Pislist = product.pislist;
            pp.PisTop = product.PIstop;
            pp.Pno = product.pno;
            pp.PDuration = pp.Ptype == 2 ? '0' : product.pDuration;

            _product_ioc._sys_product_EFCore.Update(pp);
            var res = _product_ioc._sys_product_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }
        /// <summary>
        /// 批量 /单个 删除产品类型
        /// </summary>
        /// <param name="producttype"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Delete_Product_Type(IEnumerable<string?>? ids)
        {

            var iq = await _product_ioc._sys_product_EFCore.QueryAll(d => ids!.Contains(d.Ptid)).CountAsync();
            if (iq == 0)
            {
                var data = _product_ioc._sys_Product_Type_EFCore.QueryAll(d => ids!.Contains(d.Ptid));

                _product_ioc._sys_Product_Type_EFCore.DeleteRange(data);

                var result = await _product_ioc._sys_Product_Type_EFCore.SaveChangesAsync();
                return Result(1, "删除成功");
            }

            return Result(0, "无法删除");


        }
        /// <summary>
        /// 修改产品类型
        /// </summary>
        /// <param name="producttype"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Update_Product_Type(Product_Type_Response_Dto producttype)
        {
            var pt = await _product_ioc._sys_Product_Type_EFCore.QueryAll(d => d.Ptid == producttype.id).SingleAsync();
            pt.Ptname = producttype.name;
            _product_ioc._sys_Product_Type_EFCore.Update(pt);
            var res = _product_ioc._sys_Product_Type_EFCore.SaveChanges();
            return Result(res > 0 ? 1 : 0, res > 0 ? "操作成功" : "操作失败");
        }
        /// <summary>
        /// 获取单个产品类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Product_Typeone(string id)
        {
            var pt = await _product_ioc._sys_Product_Type_EFCore.QueryAll(d => d.Ptid == id).SingleAsync();
            Product_Type_Response_Dto data = new Product_Type_Response_Dto()
            {
                createtime = pt.PtcreateTime.ToString(),
                id = pt.Ptid,
                name = pt.Ptname,
            };
            return Result(1, "ok", data: data);

        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> UploadImage(IFormFileCollection file)
        {
            if (file == null || file.Count == 0)
            {
                return Result(0, "文件为空");
            }

            // 确保上传目录存在
            var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), _configuration["Files:url"]);

            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            var fileUrls = new List<string>();
            string ss = _configuration["FileStorage:UploadPath"];
            foreach (var f in file)
            {
                if (f != null)
                {
                    var fileName = Config.GUID().ToString() + Path.GetExtension(f.FileName);
                    var filePath = Path.Combine(uploadPath, fileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await f.CopyToAsync(stream);
                    }
                    var fileUrl = $"{ss}/images/{fileName}";
                    fileUrls.Add(fileUrl);
                }
            }


            return Result(1, data: fileUrls);
            //保存文件
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> DeleteImage(IFormFileCollection file)
        {
            var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), _configuration["Files:url"]);

            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }

            foreach (var f in file)
            {

                if (f != null)
                {
                    var filePath = Path.Combine(uploadPath, f.Name);

                    await Task.Run(() => System.IO.File.Delete(filePath));
                }
            }

            return Result(1, "ok");

        }
        /// <summary>
        /// 获取所有的套餐
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Get_All_Package(int page = 1, int limit = 10, string key = "")
        {
            var iq = await _product_ioc._productPackage_EFCore.QueryAll(out int total, page, limit, false, o => o.PpTotalPrice, d => d.PpName!.Contains(key)).ToListAsync();

            var data = new List<Package_Response_Dto>();



            iq.ForEach(d =>
            {
                data.Add(new Package_Response_Dto
                {
                    id = d.PpId,
                    name = d.PpName,
                    explain = d.PpExplain,
                    Stock = d.PpStock,
                    createtime = d.PpCreateTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                    total_price = d.PpTotalPrice,
                    Discount = d.PpDiscount,
                    begintime = d.PpBeginTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                    endtime = d.PpEndTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                    isActive = d.PpIsActive,
                    desc = d.PpDesc,
                    Duration = d.PpDuration,
                    pimgs = d.PpImg?.Split(',').ToArray(),
                });
            });
            //套餐id
            var ppid=iq.Select(d=>d.PpId).ToList();
            //查询详情表里的产品id
            var pros =await  _product_ioc._productPackageDetail_EFCore.QueryAll(d => ppid.Contains(d.PpdPpId!)).ToListAsync();

           
            data.ForEach(d =>
            {
                var ppd = pros.Where(e => e.PpdPpId == d.id).Select(e => e.PpdPId).ToList();
                
                d.childrenpro = _product_ioc._sys_product_EFCore.QueryAll(d => ppd.Contains(d.Pid)).Select(d => d.Pname!).ToArray();
            });

            return Result(1, data: new
            {
                total = iq.Count(),
                data,
            });


        }
        /// <summary>
        /// 获取单个套餐的详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Get_Package_Detail(string id)
        {
            var pack= await _product_ioc._productPackage_EFCore.QueryAll(d=>d.PpId == id).SingleOrDefaultAsync();

            var iq = await _product_ioc._productPackageDetail_EFCore.QueryAll(d => id.Contains(d.PpdPpId!)).ToListAsync();

            var data = new List<package_Detail_Request_Dto>();

            if (pack != null)
            {
                data.Add(new package_Detail_Request_Dto
                {
                    pname=pack.PpName,
                    ppid=pack.PpId,
                    explain=pack.PpExplain,
                    begintime=pack.PpBeginTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                    endtime=pack.PpEndTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                    totalprice=pack.PpTotalPrice,
                    count=pack.PpStock,
                    Duration=pack.PpDuration,
                });
            }
            //产品id
            var pids=iq.Select(d=>d.PpdPId).ToList();

            data.ForEach(d => {

                d.proname=_product_ioc._sys_product_EFCore.QueryAll(d=>pids.Contains(d.Pid)).Select(d=>d.Pname).ToArray()!;

            });
          
         
            return Result(1, data: data);
        }
        /// <summary>
        /// 添加套餐
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public async Task<Api_Response_Dto> Add_Pacage(package_Request_Dto dto)
        {

            //string img = _configuration["FileStorage:UploadPath"] +dto.pimg;
            string ppid = Config.GUID();
            ProductPackage productPackage = new ProductPackage()
            {
                PpId = ppid,
                PpName = dto.name,
                PpDiscount = double.Parse(dto.Discount!),
                PpExplain = dto.explain,
                PpIsActive = 0,
                PpStock = dto.Stock,
                PpBeginTime = DateTime.Parse(dto.begintime!),
                PpCreateTime = DateTime.Now,
                PpEndTime = DateTime.Parse(dto.endtime!),
                PpDesc = dto.desc,
                PpTotalPrice = double.Parse(dto.total_price!),
                PpImg = string.Join(',', dto.pimg!),
                PpDuration=dto.Duration,
                PpSalescount = 0

            };

            var productPackageDetail = new List<ProductPackageDetail>();

            //得到添加的产品信息
            var pro = await _product_ioc._sys_product_EFCore.QueryAll(d => dto.pids!.Contains(d.Pid)).ToListAsync();

            var sum = pro.Select(d => d.Pprice).Sum();
            pro.ForEach(d =>
            {
                productPackageDetail.Add(new ProductPackageDetail
                {
                    PpdId = Config.GUID2(),
                    PpdPpId = ppid,
                    PpdPId = d.Pid,
                    PpdPrice = d.Pprice,
                    PpdQuantity = d.Pcount,
                    PpdTotalPrice = sum

                });

            });
            
            _product_ioc._productPackage_EFCore.Add(productPackage);

            _product_ioc._productPackageDetail_EFCore.AddRange(productPackageDetail);

            var res1 = await _product_ioc._productPackage_EFCore.SaveChangesAsync();

            var res2 = await _product_ioc._productPackageDetail_EFCore.SaveChangesAsync();

            return Result(1, "添加成功");


        }
     /// <summary>
     /// 上下架套餐
     /// </summary>
     /// <param name="dto"></param>
     /// <returns></returns>

        public async Task<Api_Response_Dto> isActive_Package(package_Request_Dto dto)
        {
            var iq = await _product_ioc._productPackage_EFCore.QueryAll(d => d.PpId == dto.id).SingleAsync();
            iq.PpIsActive = iq.PpIsActive == 0 ? 1 : 0;
            _product_ioc._productPackage_EFCore.Update(iq);
            var result = await _product_ioc._productPackage_EFCore.SaveChangesAsync();

            return Result(result > 0 ? 1 : 0);

        }



        /// <summary>
        /// 修改套餐
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Update_Package(package_Request_Dto dto)
        {
           var iq=await _product_ioc._productPackage_EFCore.QueryAll(d=>d.PpId==dto.id).SingleAsync();
            iq.PpName = dto.name;
            iq.PpEndTime=DateTime.Parse(dto.endtime!);
            iq.PpExplain=dto.explain;
            iq.PpStock=dto.Stock;
            iq.PpDuration = dto.Duration;
            iq.PpTotalPrice=double.Parse(dto.total_price!);
            _product_ioc._productPackage_EFCore.Update(iq);
            var result =await _product_ioc._productPackage_EFCore.SaveChangesAsync();
            return Result(result>0 ? 1 : 0);
        }

        /// <summary>
        /// 获取类型树的子级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_tree_package(string id)
        {
            var ptype = await _product_ioc._sys_Product_Type_EFCore.QueryAll(d => d.PtParentId == id).ToListAsync();

            var pro = await _product_ioc._sys_product_EFCore.QueryAll().ToListAsync();

            List<Product_Type_Response_Dto> data = new List<Product_Type_Response_Dto>();

            ptype.ForEach(d =>
            {
                data.Add(new Product_Type_Response_Dto
                {
                    id = d.Ptid,
                    name = d.Ptname,
                    disabled = true,
                    productChildren = Getchildren(d.Ptid, pro)
                });
            });


            return Result(1, data: data);

        }
        /// <summary>
        /// 获取子级产品
        /// </summary>
        /// <param name="ptid"></param>
        /// <param name="pro"></param>
        /// <returns></returns>
        private List<Product_Type_Response_Dto> Getchildren(string ptid, List<SysProduct> pro)
        {
            var children = pro.Where(d => d.Ptid == ptid && d.Pislist==1).ToList();
            var data = new List<Product_Type_Response_Dto>();
            children.ForEach(d =>
            {
                data.Add(new Product_Type_Response_Dto
                {
                    id = d.Pid,
                    name = d.Pname,
                    price = (double)d.Pprice!,
                });
            });
            return data;
        }

        /// <summary>
        /// 获取产品
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Getpro(IEnumerable<string?>? ids)
        {
            var iq =await _product_ioc._sys_product_EFCore.QueryAll(d =>ids!.Contains(d.Pid)).ToListAsync();

            List<Product_Response_Dto> data = new List<Product_Response_Dto>();

            iq.ForEach(d =>
            {

                data.Add(new Product_Response_Dto
                {
                    pname=d.Pname,
                    pprice=d.Pprice,        
                });

            });

           

            return Result(1, data: data);
        }
    }
}
